﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using Utils.Documentation;

namespace DocuGenerator
{
	static class Extensions
	{
		public static string GetTypeName(this Type that)
		{
			var genericArguments = that.GetGenericArguments();
			if (genericArguments.Any())
			{
				return that.GetFormatedTypeName() + "<" 
					+ genericArguments.Select(GetTypeName).Aggregate((a, b) => a + ", " + b) 
					+ ">";
			}

			return that.GetFormatedTypeName();
		}

		public static string GetMethodName(this MethodBase that)
		{
			var genericArguments = that.GetGenericArguments();
			if (genericArguments.Any())
			{
				return that.Name + "<"
					+ genericArguments.Select(GetTypeName).Aggregate((a, b) => a + ", " + b)
					+ ">";
			}

			return that.Name;
		}

		public static bool CanLinkTo(this Type that)
		{
			return that.Namespace.StartsWith("Byond");
		}

		private static string GetFormatedTypeName(this Type that)
		{
			var name = that.Namespace.StartsWith("Byond") || that.Namespace.Equals("System")
				? that.Name
				: that.FullName;
			var args = that.GetGenericArguments();
			return args.Any()
				? name.Replace("`" + args.Length, "") 
				: name;
		}

		public static DocAttribute Doc(this MemberInfo that, bool includeInherited = true)
		{
			return that.GetCustomAttributes(includeInherited).OfType<DocAttribute>().FirstOrDefault();
		}
	}
}
